package com.example.sharesinfo.utils;

import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;


import com.example.sharesinfo.BuildConfig;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Date;

public class LogUtils {
    // Fields from build type: debug
    public static final boolean LOG_DEBUG = true;
    public static final String LOG_TAG = "ShareInfo";
    public static final String SP_NAME = "Config";
    //LogUtils.i("");
    /*
     * Log不光作为日志的打印，还可以记录日志：通过File记录
     * */
    private static SimpleDateFormat mSimpleDateFormat =
            new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public static void i(String text) {
        //if判断的先后顺序
        if (LOG_DEBUG) {
            if (!TextUtils.isEmpty(text)) {
                Log.i(LOG_TAG, text);
                //writeToFile(text);
            }
        }
    }

    public static void e(String text) {
        //if判断的先后顺序
        if (LOG_DEBUG) {
            if (!TextUtils.isEmpty(text)) {
                Log.e(LOG_TAG, text);
                //writeToFile(text);
            }
        }
    }

    private static void writeToFile(String text) {

        //文件路径
        String fileName = "/sdcard/ShareInfo/ShareInfo.log";
        //时间 内容
        String log = mSimpleDateFormat.format(new Date()) + " " + text + "\n";
        //检查父路径
        File fileGroup = new File("/sdcard/ShareInfo/");
        if (!fileGroup.exists()) {
            fileGroup.mkdirs();
            /*mkdir()是创建子目录。
             *mkdirs()是创建多级目录。
             * */
        }
        //开始写入
        FileOutputStream fileOutputStream = null;
        BufferedWriter bufferedWriter = null;
        try {
            //append true表示表示续写
            fileOutputStream = new FileOutputStream(fileName, true);
            //编码，GBK才能正确的存入中文
            bufferedWriter = new BufferedWriter(
                    new OutputStreamWriter(fileOutputStream, Charset.forName("gbk")));
            bufferedWriter.write(log);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //释放
            if (bufferedWriter != null) {
                try {
                    bufferedWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

